package com.xtecher.app.column.ui;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawable;
import android.support.v4.graphics.drawable.RoundedBitmapDrawableFactory;
import android.support.v4.widget.Space;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader2.RecyclerViewHeader;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.target.BitmapImageViewTarget;
import com.githang.statusbar.StatusBarCompat;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.xtecher.app.R;
import com.xtecher.app.base.BaseActivity;
import com.xtecher.app.column.ColumnContact;
import com.xtecher.app.column.ColumnPresenter;
import com.xtecher.app.column.adapter.ColumnListAdapter;
import com.xtecher.app.column.bean.ColumnListResponse;
import com.xtecher.app.user.FollowUtils;
import com.xtecher.app.user.bean.FollowUserResponse;
import com.xtecher.app.utils.RecyclerUtils;
import com.xtecher.app.utils.StatusBarUtil;
import com.xtecher.app.widget.OnItemClickListener;
import com.xtecher.app.widget.glide.BlurTransformation;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

/**
 * 关注的人所有的文章
 */
public class ColumnListActivity extends BaseActivity implements ColumnContact.View {

    private ColumnPresenter presenter;
    private String url = "";
    private FollowUserResponse user;
    private RecyclerViewHeader header;
    private ImageView imgBg;
    private ImageView imgAvatar;
    private RecyclerView reNews;
    private RelativeLayout reTop;
    private View divider;
    private TextView tvName;
    private ImageView imgBack;
    private ImageView imgFollow;
    private Space space;
    private Space spaceFix;
    private List<ColumnListResponse> columnListResponses;
    private ColumnListAdapter listAdapter;
    private String lastId = "";
    private SwipeRefreshLayout refreshLayout;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_colun_list);

        StatusBarUtil.StatusBarLightMode(this);
        //在setContentView之后调用
        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        /*ViewGroup viewGroup = (ViewGroup) this.findViewById(Window.ID_ANDROID_CONTENT);
        View childView = viewGroup.getChildAt(0);
        if (null != childView) {
            ViewCompat.setFitsSystemWindows(childView, false);
        }*/

        user = getIntent().getParcelableExtra("user");
        initView();
        initLisneter();
        presenter = new ColumnPresenter(this);
        isRefresh = true;
        url = String.format("?uid=%s&from=%S", user.getUid(), "0");
        presenter.getArticleList(url);

    }

    private void initLisneter() {
        imgBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ColumnListActivity.this.onBackPressed();
            }
        });

        imgFollow.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                FollowUtils.clearFollow(ColumnListActivity.this, user.getUid());
                finish();
            }
        });
        reNews.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
                //判断下滑距离确定顶部状态栏和操作栏展示
                if (getScollYDistance(reNews) > -(header.getHeight() / 2)) {
                    divider.setVisibility(View.VISIBLE);
                    reTop.setBackgroundResource(R.color.white);
                    imgBack.setImageResource(R.mipmap.back);
                    imgFollow.setImageResource(R.mipmap.black_following);
                    imgFollow.setBackgroundResource(R.drawable.border_333);
                    space.setVisibility(View.GONE);
                    spaceFix.setVisibility(View.GONE);
                    StatusBarCompat.setStatusBarColor(ColumnListActivity.this, Color.WHITE);
                } else {
                    space.setVisibility(View.VISIBLE);
                    spaceFix.setVisibility(View.VISIBLE);
                    Window window = ColumnListActivity.this.getWindow();
                    window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                    divider.setVisibility(View.GONE);
                    reTop.setBackgroundResource(R.color.transparent);
                    imgBack.setImageResource(R.mipmap.white_ack);
                    imgFollow.setImageResource(R.mipmap.following);
                    imgFollow.setBackgroundResource(R.drawable.border_fff);
                }
                //判断是否滑动到底部
                if (RecyclerUtils.isSlideToBottom(reNews) && !TextUtils.isEmpty(lastId)) {
                    loading = true;
                    url = String.format("?uid=%s&from=%s", user.getUid(), lastId);
                    presenter.getArticleList(url);
                    lastId = "";
                }
            }
        });

        refreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isRefresh = true;
                url = String.format("?uid=%s&from=%S", user.getUid(), "0");
                presenter.getArticleList(url);
            }
        });
    }

    public int getScollYDistance(RecyclerView re) {
        LinearLayoutManager layoutManager = (LinearLayoutManager) re.getLayoutManager();
        int position = layoutManager.findFirstVisibleItemPosition();
        View firstVisiableChildView = layoutManager.findViewByPosition(position);
        int itemHeight = firstVisiableChildView.getHeight();
        return (position) * itemHeight - firstVisiableChildView.getTop();
    }

    private void initView() {
        refreshLayout = (SwipeRefreshLayout) findViewById(R.id.refreshLayout);
        header = (RecyclerViewHeader) findViewById(R.id.header);
        imgBg = (ImageView) findViewById(R.id.img_bg);
        imgAvatar = (ImageView) findViewById(R.id.img_avatar);
        reNews = (RecyclerView) findViewById(R.id.re_news);
        reTop = (RelativeLayout) findViewById(R.id.re_top);
        tvName = (TextView) findViewById(R.id.tv_name);
        divider = findViewById(R.id.divider);
        imgBack = (ImageView) findViewById(R.id.img_back);
        imgFollow = (ImageView) findViewById(R.id.img_follow);
        space = (Space) findViewById(R.id.space);
        spaceFix = (Space) findViewById(R.id.space_fix);
        reNews.setLayoutManager(new LinearLayoutManager(this));
        header.attachTo(reNews);
        Glide.with(this)
                .load(user.getAvatar())
                .asBitmap()
                .centerCrop()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .into(new BitmapImageViewTarget(imgAvatar) {
                    @Override
                    protected void setResource(Bitmap resource) {
                        RoundedBitmapDrawable circularBitmapDrawable =
                                RoundedBitmapDrawableFactory.create(getResources(), resource);
                        circularBitmapDrawable.setCircular(true);
                        imgAvatar.setImageDrawable(circularBitmapDrawable);
                    }
                });

        Glide.with(this)
                .load(user.getAvatar())
                .centerCrop()
                .bitmapTransform(new BlurTransformation(this, 25))
                .into(imgBg);
        tvName.setText(user.getName());
        columnListResponses = new ArrayList<>();
        listAdapter = new ColumnListAdapter(this, columnListResponses);
        listAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view1, int position) {
                Intent intent = new Intent(ColumnListActivity.this, ColumnDetailActivity.class);
                intent.putExtra("aid", columnListResponses.get(position).getId());
                ColumnListActivity.this.startActivity(intent);
            }
        });
        reNews.setAdapter(listAdapter);
    }

    @Override
    public void setData(Object o, @Nullable int id) {
        switch (id) {
            case 0:
                if (columnListResponses != null && columnListResponses.size() == 0) {
                    isRefresh = true;
                }
                Type type = new TypeToken<List<ColumnListResponse>>() {
                }.getType();
                List<ColumnListResponse> responses = new Gson().fromJson(String.valueOf(o), type);
                if (responses != null && responses.size() > 0) {
                    if (isRefresh) {
                        columnListResponses.clear();
                        columnListResponses.addAll(responses);
                    }
                    if (loading) {
                        columnListResponses.addAll(responses);
                    }
                    listAdapter.notifyDataSetChanged();
                    lastId = String.valueOf(responses.get(responses.size() - 1).getId());
                }

                break;
        }
    }

    @Override
    public void hideLoading() {
        super.hideLoading();
        if (isRefresh) {
            isRefresh = false;
            refreshLayout.setRefreshing(false);
        }
        if (loading) {
            loading = false;
        }
    }
}
